package org.apereo.cas.web.flow;

import java.util.ArrayList;

import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.web.flow.configurer.AbstractCasWebflowConfigurer;
import org.springframework.context.ApplicationContext;
import org.springframework.webflow.definition.registry.FlowDefinitionRegistry;
import org.springframework.webflow.engine.ActionState;
import org.springframework.webflow.engine.Flow;
import org.springframework.webflow.engine.builder.support.FlowBuilderServices;
import org.springframework.webflow.execution.Action;

import lombok.val;
import lombok.extern.slf4j.Slf4j;

/**
 * 参照 cas-server-support-captcha模块做修改
 * 
 * @description
 * @author linzl
 * @email 2225010489@qq.com
 * @date 2018年7月25日
 */
@Slf4j
public class CasKaptchaWebflowConfigurer extends AbstractCasWebflowConfigurer {

	public CasKaptchaWebflowConfigurer(final FlowBuilderServices flowBuilderServices,
			final FlowDefinitionRegistry loginFlowDefinitionRegistry, final ApplicationContext applicationContext,
			final CasConfigurationProperties casProperties) {
		super(flowBuilderServices, loginFlowDefinitionRegistry, applicationContext, casProperties);
	}

	@Override
	protected void doInitialize() {
		Flow flow = getLoginFlow();
		if (flow != null) {
			log.debug("验证码流程绑定");
			createValidateKaptchaAction(flow);
		}
	}

	private void createValidateKaptchaAction(final Flow flow) {
		val state = getState(flow, CasWebflowConstants.STATE_ID_REAL_SUBMIT, ActionState.class);
		val currentActions = new ArrayList<Action>();
		state.getActionList().forEach(currentActions::add);
		currentActions.forEach(a -> state.getActionList().remove(a));

		state.getActionList().add(createEvaluateAction("validateKaptchaAction"));
		currentActions.forEach(a -> state.getActionList().add(a));
		state.getTransitionSet().add(createTransition("captchaError", CasWebflowConstants.STATE_ID_INIT_LOGIN_FORM));
	}
}
